package cn.tjad.tjad2.net.fileupload;

import android.content.Context;

import com.hjy.http.upload.FileUploadConfiguration;
import com.hjy.http.upload.FileUploadManager;
import com.hjy.http.upload.listener.OnUploadListener;
import com.hjy.http.upload.listener.OnUploadProgressListener;
import com.hjy.http.upload.uploader.BaseUploader;
import com.hjy.http.upload.uploader.OKHttpUploader;

import java.util.Map;

import cn.tjad.tjad2.application.TjadApplication;

public class FileUploader {

    private boolean isInit = false;

    private volatile static FileUploader instance;

    private FileUploadConfiguration fileUploadConfiguration;

    private FileUploader() {

    }

    public static FileUploader getInstance() {
        if (instance == null) {
            synchronized (FileUploader.class) {
                if (instance == null) {
                    instance = new FileUploader();
                }
            }
        }
        return instance;
    }

    public void init(Context context) {
        if (!isInit) {
             fileUploadConfiguration = new FileUploadConfiguration.Builder(context.getApplicationContext())
                    .setThreadPoolSize(5)
                    .setThreadPriority(Thread.NORM_PRIORITY - 1)
                    .setResponseProcessor(new FileUploadResponeParser())
                    .build();
            FileUploadManager.getInstance().init(fileUploadConfiguration);
            if (TjadApplication.getInstance().getSession() != null) {
                setSession(TjadApplication.getInstance().getSession().getToken());
            }
            isInit = true;
        }
    }

    public void setSession(String session) {
        if (fileUploadConfiguration == null) {
            throw new RuntimeException("请先调用init()方法");
        }
        BaseUploader uploader = fileUploadConfiguration.getFileUploader();
        if (uploader instanceof OKHttpUploader) {
            ((OKHttpUploader) uploader).setToken(session);
        }
    }

    public void uploadFile(Map<String, String> params, String id, String path, String mimeType, String url, OnUploadListener apiCallback, OnUploadProgressListener uploadProgressListener) {
        FileUploadManager.getInstance().uploadFile(null, params, id, path, mimeType, url, apiCallback, uploadProgressListener, null);
    }
}
